from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.responses import FileResponse
import os
import subprocess
import uuid
import tempfile

app = FastAPI()

# 创建一个自定义的 LaTeX 模板
LATEX_TEMPLATE = r"""
\documentclass{article}
\usepackage{amsmath}
\usepackage[utf8]{inputenc}
\usepackage{xcolor}

\begin{document}
$body$$
\end{document}
"""

@app.post("/convert/")
async def convert_markdown_to_docx(file: UploadFile = File(...)):
    # 生成唯一的文件名
    input_filename = f"{uuid.uuid4()}.md"
    output_filename = f"{uuid.uuid4()}.docx"
    temp_latex_file = f"{uuid.uuid4()}.tex"

    # 保存上传的文件到磁盘
    with open(input_filename, "wb") as f:
        f.write(await file.read())

    # 创建临时 LaTeX 模板文件
    with open(temp_latex_file, "w") as f:
        f.write(LATEX_TEMPLATE)

    # 使用 Pandoc 将 Markdown 转换为 DOCX
    try:
        subprocess.run([
            "pandoc",
            "-o", output_filename,
            "-f", "markdown",
            "-t", "docx",
            "--pdf-engine=xelatex",
            "--standalone",
            f"--template={temp_latex_file}",
            "--mathjax",
            input_filename
        ], check=True)
    except subprocess.CalledProcessError as e:
        raise HTTPException(status_code=500, detail="Conversion failed")

    # 删除临时文件
    os.remove(input_filename)
    os.remove(temp_latex_file)

    # 返回转换后的 DOCX 文件
    return FileResponse(output_filename, media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                        filename="output.docx")

@app.get("/status/")
def status_check():
    return {"status": "Service is running"}

@app.on_event("shutdown")
def cleanup():
    # 删除服务运行期间创建的所有 .docx 文件
    for filename in os.listdir("."):
        if filename.endswith(".docx"):
            os.remove(filename)
